﻿package net.wangit.support;

import java.sql.Connection;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.jasperreports.engine.JRAbstractExporter;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.wangit.framework.util.ResponseWriter;
import net.wangit.util.Checker;
import net.wangit.view.report.ReportExporter;
import net.wangit.view.report.ReportSettings;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


/**
 * 报表解析类。
 * 
 * @author watson Feb 25, 2010
 */
public class ReportWriter {

	private static final Log log = LogFactory
			.getLog(net.wangit.support.ReportWriter.class);
	private static final String SQL_PARAMETER_NAME = "sql";

	public ReportWriter() {
	}

	// 输出报表。
	public void write(HttpServletRequest request, HttpServletResponse response,
			JasperReport jasperReport, ReportSettings settings) {
		try {
			Map<String, String> parameters = new HashMap<String, String>();
			String sql = settings.getSql();
			if (!Checker.isEmpty(sql))
				parameters.put(ReportWriter.SQL_PARAMETER_NAME, sql);
			setParameters(request, parameters);
			Connection connection = settings.getConnection();
			JasperPrint jasperPrint = fill(jasperReport, parameters, connection);
			ReportExporter reportExporter = settings.getExporter();
			JRAbstractExporter exporter = reportExporter.createExporter();
			exporter
					.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
			exporter.setParameter(JRExporterParameter.START_PAGE_INDEX,
					settings.getStartPageIndex());
			exporter.setParameter(JRExporterParameter.END_PAGE_INDEX, settings
					.getEndPageIndex());
			setExporter(exporter);
			reportExporter.export(exporter, response);
		} catch (Exception e) {
			log.error(e);
			ResponseWriter.write("could not write report!");
		}
	}

	// 此方法是一个空方法，子类可用来设置报表参数，设置于Map对象中。
	protected void setParameters(HttpServletRequest httpservletrequest, Map<String, String> map) {
	}

	// 报表对象填充。
	protected JasperPrint fill(JasperReport jasperReport, Map<String, String> parameters,
			Connection connection) throws Exception {
		return JasperFillManager.fillReport(jasperReport, parameters,
				connection);
	}

	// 此方法是一个空方法，子类可用来设置JRAbstractExporter。
	protected void setExporter(JRAbstractExporter jrabstractexporter) {
	}

}
